package util;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import object.Command;
import object.Command.CommandType;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import voice.main.R;
import android.content.res.Resources;

public class XMLParser {
	public static Command GetCommandList(CommandType commandType, Resources resources) {
        try 
        {
            InputStream in = resources.openRawResource(R.raw.commands);   
        	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        	DocumentBuilder builder = factory.newDocumentBuilder();
        	Document dom = builder.parse(in, "UTF-8");
        	XPathFactory xPathfactory = XPathFactory.newInstance();
        	XPath xpath = xPathfactory.newXPath();
        	XPathExpression expr = xpath.compile("/Commands/CommandType[@type='" + commandType.toString() + "']");
        	Element commandNode = (Element) expr.evaluate(dom, XPathConstants.NODE);
        	String response = commandNode.getAttribute("response");
        	expr = xpath.compile("/Commands/CommandType[@type='" + commandType.toString() + "']/Command");
        	NodeList items = (NodeList) expr.evaluate(dom, XPathConstants.NODESET);
        	List<String> results = new ArrayList<String>();
		    for (int i=0;i<items.getLength();i++)
		    {
		    	results.add(items.item(i).getTextContent());
		    }
		    return new Command(results, response);
        }
        catch (Exception e) 
        {
    	    return null;
        } 
	}
}
